package cn.cityre.tools.crestat;

import cn.cityre.tools.db.DynamicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author sunzhaoye
 */
public abstract class BaseStatWorker implements StatWorker {
	private final static Logger log = LoggerFactory.getLogger(BaseStatWorker.class);
	public final Queue<String> items = new ConcurrentLinkedQueue<>();
	public final DynamicDataSource dataSource;

	protected BaseStatWorker(DynamicDataSource dataSource) {
		this.dataSource = dataSource;
	}

	private TaskExecutor taskExecutor;
	private int threadCount;


	@Override
	public void work() {


		int startSize = items.size();

		for (int i = 0; i < threadCount; i++) {
			taskExecutor.execute(createWorker(i));
		}

		ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) taskExecutor;
		int oldprocess = -1;
		for (;;) {
			int count = executor.getActiveCount();
			try {
				Thread.sleep(2000);
				int process = (int) ((startSize * 1.0 - items.size()) / startSize * 100.0);
				if (oldprocess != process) {
					log.info("progress {}", process + "%");
					oldprocess = process;
				}
			} catch (InterruptedException e) {
				executor.shutdown();
				break;
			}
			if (count == 0) {
				executor.shutdown();
				break;
			}
		}
	}

	protected abstract Runnable createWorker(int idx);

	@Override
	public void beforeWork(ApplicationContext context, Environment env) {
		/**
		 * s
		 */
		taskExecutor = (TaskExecutor) context.getBean("taskExecutor");

		threadCount = Integer.parseInt(env.getProperty("stat.threadcount", "1"));

	}

}
